package Singleton;

import sun.misc.Unsafe;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Constructor;

public class Test {
    public static void main(String[] args) throws Exception {
        //singleton1();
        singleton3();
    }

    public static void singleton3(){
        Singleton3.otherMethod();
        System.out.println("==========================");
        System.out.println(Singleton3.getInstance());
        System.out.println(Singleton3.getInstance());
    }

    public static void singleton2(){
        System.out.println(Singleton2.getInstance());
    }

    public static void singleton1() throws Exception {
        Singleton1.otherMethod();
        System.out.println("===============================");
        System.out.println(Singleton1.getInstance());
        System.out.println(Singleton1.getInstance());

        // 破坏单例  通过反射获取构造方法
        //reflection(Singleton1.class);

        // 反序列化
        serializale(Singleton1.getInstance());

        //unsafe
        unsafe(Singleton1.getInstance().getClass());
    }


    // 反射创建实例
    public static void reflection(Class<?> clazz) throws Exception {
        Constructor<?> constructor = clazz.getDeclaredConstructor();
        constructor.setAccessible(true);  // 允许访问私有
        System.out.println("反射创建实例：" + constructor.newInstance());
    }

    // 反序列化创建实例
    public static void serializale(Object instance) throws Exception {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(instance);
        ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));
        System.out.println("反序列化创建实例："+ois.readObject());
    }

    // unsafe类破坏单例
    public static void unsafe(Class<?> clazz) throws Exception {
        Object instance = Unsafe.getUnsafe().allocateInstance(clazz);
        System.out.println("unsafe类 创建实例："+instance);
    }
}
